moment = require 'moment'
moment.locale "zh-cn"
co = require 'co'
Promise = require 'bluebird'

log = require './log'
web = require './web'
sql = require './storage/Mysql'
mongo = require './storage/Mongo'
config = require './config'

EntityServiceCache = require './service/EntityServiceCache'

webStarted = false

extensions = []

gInitExtensions = ->
    fs = require('fs')
    pReaddir = Promise.promisify fs.readdir.bind(fs)
    pStat = Promise.promisify fs.stat.bind(fs)

    extensionDir = __dirname + "/extension"
    log.system.info 'extension dir: ' + extensionDir
    stats = yield pStat(extensionDir)
    return unless stats.isDirectory()

    extensions = []
    files = yield pReaddir extensionDir
    for dir in files
        dirPath = extensionDir + "/" + dir
        stats = yield pStat dirPath
        continue unless stats.isDirectory()
        extensions.push require(dirPath)

closeSystem = ->
    log.system.info "!!!ASKED TO STOP!!!"
    if webStarted
        # 先等待服务器关闭，再关闭 Mongo 等
        web.stop()
    else
        stop()

process.on 'SIGINT', closeSystem
process.on 'SIGTERM', closeSystem

gStop = ->
    log.system.info '=== Web Server Closed'

    EntityServiceCache.stopCleanTimer()

    yield from require('./service/PromotionService').gPersist()

    for e in extensions
        try
            yield from e.gStopComponents() if e.gStopComponents
        catch e
            log.system.error e, 'stop extension component'

    yield from mongo.gDispose()
    yield from sql.gEnd() if config.mysql

    log.system.info '===== !!! SYSTEM DOWN !!! ========================='
    console.log '===== !!! SYSTEM DOWN !!! ========================='

stop = -> co(gStop).catch (e) -> log.system.error(e, 'stop')

gStart = ->
    yield from require('./meta/Meta').gLoad()

    # 先加载元数据、再自动创建 MySQL ，最后再创建索引
    yield from require('./storage/RefactorMysqlTable').gSyncSchema() if config.mysql

    yield from require('./storage/MongoIndex').gSyncWithMeta()
    yield from require('./storage/MysqlIndex').gSyncWithMeta() if config.mysql

    yield from require('./service/SystemService').gInit()

    yield from require('./service/UserService').gInit()

    yield from require('./service/SeoSerivce').gInit()

    EntityServiceCache.startCleanTimer()

    yield from gInitExtensions()

    log.system.info 'System components started!'

    for e in extensions
        yield from e.gStartComponents() if e.gStartComponents

    log.system.info 'All components started!'

    web.init(extensions, stop)

    # 开始监听
    yield from web.start()
    webStarted = true

    log.system.info '===== !!! SYSTEM UP !!! ========================='
    console.log '===== !!! SYSTEM UP !!! ========================='

co(gStart).catch (e) ->
    stop()
    log.system.error(e, 'start')





